package com.suning.sawp.service.listener;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.suning.framework.dal.client.DalClient;
import com.suning.rsc.dto.responsedto.MbfServiceResponse;
import com.suning.rsc.mqservice.ei.annotation.EsbEIServerService;
import com.suning.rsc.server.NullResponseDto;
import com.suning.rsc.server.mq.MQServerServiceHandler;
import com.suning.sawp.constants.CacheKeyConstants;
import com.suning.sawp.dto.common.NsfNullReponseInterfaceForEsb;
import com.suning.sawp.dto.esb.NsfStoreMqDto;
import com.suning.sawp.dto.esb.StoreBaseInfoDto;
import com.suning.sawp.po.store.StoreInfo;
import com.suning.sawp.service.util.RedisCacheUtils;

/**
 * 
 * 监听门店数据mq接口<br> 
 * 服务编码    StoreService-syncStoreInfo
 *
 * @author 14062606
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@EsbEIServerService(connectionFactory = "snsawpConnectionFactory", receiveQueue = "receiveStoreBDQueue")
public class StoreBaseInfoReceiveListener extends MQServerServiceHandler<NsfStoreMqDto, NullResponseDto, NsfNullReponseInterfaceForEsb>{
	
	private static final Logger LOGGER = LoggerFactory.getLogger(StoreBaseInfoReceiveListener.class);
	
	@Resource
    MongoTemplate mongoTemplate;
	
	@Autowired
	RedisCacheUtils   cacheUtils;
	
	@Resource
	DalClient dalClient;
	
	@Override
	public NullResponseDto handleBizz(NsfStoreMqDto input,
			String uid) {
		LOGGER.debug("StoreBaseInfoReceiveListener接收数据：{},uid:{}", input, uid);
		if (null != input) {
		    // 判断操作标识是否为删除
		    if (StringUtils.isNotBlank(input.getOperationFlag())
                    && "D".equals(input.getOperationFlag())) {
		        if (null != input.getStoreBaseInfo()
                        && StringUtils.isNotBlank(input.getStoreBaseInfo().getStoreId())) {
		            delStoreInfo(input.getStoreBaseInfo());
                }
		    } else {
		        // 其他场景走新增更新
                // 数据库对应bean赋值
                StoreBaseInfoDto dto = input.getStoreBaseInfo();
                if (null != dto) {
                    addOrUpdateStoreInfo(dto);
                    //新增门店数据变更 更新缓存
                    cacheUtils.clearCacheData(CacheKeyConstants.STORE_INFO, dto.getStoreSaleCode());
                }
		    }
		    cacheUtils.clearCacheData(CacheKeyConstants.BRANCH_BY_REGION);
		    cacheUtils.clearCacheData(CacheKeyConstants.STORE_BY_BRANCH);
		    cacheUtils.clearCacheData(CacheKeyConstants.STORE_TREE);
		}
		
		return null;
	}

	/**
	 * 对推送过来的数据做新增或者更新操作
	 * @param shopInfo
	 */
	private void addOrUpdateStoreInfo(StoreBaseInfoDto storeInfo){
		Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and("storeCode").is(storeInfo.getStoreSaleCode());
        query.addCriteria(criteria);
        Update update = new Update();
        update.set("storeCode", storeInfo.getStoreSaleCode());
        update.set("storeName", storeInfo.getStoreName());
        /**update.set("cityComCode", storeInfo.getCityCode());**/
        update.set("cityComName", storeInfo.getCityName());
        update.set("regionCode", storeInfo.getRegionCode());
        update.set("regionName", storeInfo.getRegionName());
        update.set("branchCode", storeInfo.getCompanyCode());
        update.set("branchName", storeInfo.getCompanyName());
        //增加4个字段 --wuxiao
        update.set("saleBranchCode", storeInfo.getCompanySaleCode());
        update.set("storeLevel", storeInfo.getStoreLevel());
        update.set("storeTypeName", storeInfo.getStoreTypeName());
        update.set("storeTypeCode", storeInfo.getStoreTypeId());
		mongoTemplate.upsert(query, update, StoreInfo.class);
		
		// 同步在mysql中建一张表
		// 取5位财务大区编码
		String saleRegionCode = "";
		if (null != storeInfo && StringUtils.isNotBlank(storeInfo.getRegionCode())) {
		    Map<String, Object> params = new HashMap<String, Object>();
		    params.put("region8cd", storeInfo.getRegionCode());
		    String region5cd = dalClient.queryForObject("MAIN_DISCODE.QUERY_5_CODE_BY_8_CD", params, String.class);
		    saleRegionCode = StringUtils.isNotBlank(region5cd) ? region5cd : "";
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeInfo.getStoreSaleCode());
        paramMap.put("storeName", storeInfo.getStoreName());
        paramMap.put("regionCode", storeInfo.getRegionCode());
        paramMap.put("saleRegionCode", saleRegionCode);
        paramMap.put("regionName", storeInfo.getRegionName());
        paramMap.put("branchCode", storeInfo.getCompanyCode());
        paramMap.put("branchName", storeInfo.getCompanyName());
        paramMap.put("saleBranchCode", storeInfo.getCompanySaleCode());
        paramMap.put("storeLevel", storeInfo.getStoreLevel());
        paramMap.put("storeTypeName", storeInfo.getStoreTypeName());
        paramMap.put("storeTypeCode", storeInfo.getStoreTypeId());
        paramMap.put("updateTime", new Date());
        dalClient.execute("STORE_BASE_INFO.REPLACE", paramMap);
	}
	
	/**
	 * 根据推送过来的删除标记对数据做删除操作
	 * @param shopInfo
	 */
	private void delStoreInfo(StoreBaseInfoDto storeInfo){
		Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and("storeCode").is(storeInfo.getStoreSaleCode());
        query.addCriteria(criteria);
        mongoTemplate.remove(query, StoreInfo.class);
        
        // 同步在mysql中建一份表
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeInfo.getStoreSaleCode());
        dalClient.execute("STORE_BASE_INFO.DEL_STORE", paramMap);
	}
	
	@Override
	public void sendResponse(NsfNullReponseInterfaceForEsb clientInterface,
			NullResponseDto response, MbfServiceResponse serviceResponse) {
		LOGGER.info("for sonar temporary");
	}
	
}
